
import { LoginQuery } from '../services/login'
import { Toast } from 'antd-mobile'
import { Actions } from 'react-native-router-flux'
function showToast(){
    Toast.fail('用户名或密码错误！', 1)
}
export default {
    namespace: 'mylogin',

    state: {
        userId: 'f1ce0151658846798f84d1ddb0c3bdc5',
        userName: '柴浩',
        pwd: '123456',
        role: '监督员',
        confirm: false,
        loading: false,
    },

    subscriptions: {
        setup({dispatch, history}){
        },
    },

    effects: {
        *login({payload}, {put, select, call}){

            yield put({type: 'startLoading'})

            const { userName, pwd } = yield select(state => state.login)

            /**
             * 请求参数：userName(用户名)，pwd(密码)
             */
            const { json, error } = yield call(LoginQuery, {loginName: userName, password: pwd})

            if(error || json.code === '0'){
                yield put({type: 'stopLoading'})
                showToast()
            }else{
                yield put({type: 'stopLoading'})
                yield put({type: 'loginSuccess', payload: json.data})
                Actions.push('IndexPage')
            }
        }
    },

    reducers: {
        change(state, {payload}){
            return { ...state, ...payload}
        },
        startLoading(state){
            return { ...state, loading: true }
        },
        stopLoading(state){
            return { ...state, loading: false }
        },
        loginSuccess(state, {payload}){
            return { ...state, userId: payload.id, userName: payload.name, role: payload.roleNames, confirm: true }
        }
    },
}